import { Component } from './Component';
import { Entity } from './Entity';
import { World } from './World';

// 视图数据变化事件
export class ComponentViewDataChangedEvent {
    constructor(
        public readonly component: Component,
        public readonly data: any,
        public readonly oldData: any
    ) {}
}

// 视图管理器
export class ComponentViewManager {
    private _componentViews = new Map<new () => Component, Set<Component>>();
    private _viewCallbacks = new Map<Component, Set<(data: any) => void>>();

    // 注册组件的视图
    public registerView(component: Component): void {
        const type = component.constructor as new () => Component;
        if (!this._componentViews.has(type)) {
            this._componentViews.set(type, new Set());
        }
        this._componentViews.get(type)!.add(component);
    }

    // 注销组件的视图
    public unregisterView(component: Component): void {
        const type = component.constructor as new () => Component;
        const views = this._componentViews.get(type);
        if (views) {
            views.delete(component);
            if (views.size === 0) {
                this._componentViews.delete(type);
            }
        }
        this._viewCallbacks.delete(component);
    }

    // 订阅组件数据变化
    public subscribe(component: Component, callback: (data: any) => void): void {
        if (!this._viewCallbacks.has(component)) {
            this._viewCallbacks.set(component, new Set());
        }
        this._viewCallbacks.get(component)!.add(callback);
    }

    // 取消订阅组件数据变化
    public unsubscribe(component: Component, callback: (data: any) => void): void {
        const callbacks = this._viewCallbacks.get(component);
        if (callbacks) {
            callbacks.delete(callback);
            if (callbacks.size === 0) {
                this._viewCallbacks.delete(component);
            }
        }
    }

    // 通知组件数据变化
    public notifyDataChanged(component: Component, data: any, oldData: any): void {
        // 触发回调
        const callbacks = this._viewCallbacks.get(component);
        if (callbacks) {
            callbacks.forEach(callback => callback(data));
        }

        // 发送事件
        if (component.entity?.world) {
            component.entity.world.triggerEvent(new ComponentViewDataChangedEvent(component, data, oldData));
        }
    }

    // 获取组件的所有视图
    public getViews<T extends Component>(type: new () => T): Set<T> {
        return (this._componentViews.get(type) as Set<T>) || new Set();
    }

    // 获取实体的组件视图
    public getEntityView<T extends Component>(entity: Entity, type: new () => T): T | undefined {
        const views = this.getViews(type);
        for (const view of views) {
            if (view.entity === entity) {
                return view;
            }
        }
        return undefined;
    }
} 